<template>
  <div class="app-container">
    <el-row>
      <el-col :span="24" class="card-box">
        <el-card>
          <div class="head-row">
            <div class="head">统计图表展示</div>
            <div class="tab">
              <div
                :class="current === 0 ? 'tab-item active' : 'tab-item'"
                @click="
                  current = 0;
                  getUserList();
                "
              >
                民警统计
              </div>
              <div
                :class="current === 1 ? 'tab-item active' : 'tab-item'"
                @click="
                  current = 1;
                  getComData();
                "
              >
                社区统计
              </div>
            </div>
          </div>
          <template v-if="current === 0">
            <el-row class="mt1">
              <el-form-item label="民警" prop="badgeNumber">
                <el-select
                  v-model="policeUserId"
                  filterable
                  placeholder="请输入民警姓名或警号搜索"
                  style="width: 240px"
                  @change="initUserConStat"
                >
                  <el-option
                    v-for="item in polices"
                    :key="item.policeUserId"
                    :label="`${item.userName}-${item.badgeNumber}`"
                    :value="item.policeUserId"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="时间" class="ml4">
                <el-date-picker
                  v-model="userYears"
                  type="year"
                  placeholder="请选择"
                  format="YYYY年"
                  value-format="YYYY"
                  @change="getUserList"
                />
              </el-form-item>
              <el-form-item class="ml4">
                <el-button type="primary" icon="Search" @click="getUserList"
                  >查询</el-button
                >
                <el-button icon="Refresh" @click="resetQuery">重置</el-button>
              </el-form-item>
            </el-row>
            <el-row class="mt1" :gutter="50">
              <el-col :span="12">
                <div ref="evayear" style="height: 300px" />
              </el-col>
              <el-col :span="12">
                <div ref="evanum" style="height: 300px" />
              </el-col>
            </el-row>
          </template>
          <template v-if="current === 1">
            <el-row class="mt1">
              <el-col :span="12">
                <div class="flex-row mt10">
                  月统计
                  <div class="label">时间：</div>
                  <el-date-picker
                    v-model="monthQuery.yearMonth"
                    type="month"
                    placeholder="请选择"
                    format="YYYY年MM月"
                    value-format="YYYY-MM"
                    @change="initMonthStat"
                  />
                </div>
              </el-col>
            </el-row>
            <el-row class="mt1">
              <el-col :span="12">
                <div
                  class="el-table el-table--enable-row-hover el-table--medium"
                >
                  <div ref="consulttotalmonth" style="height: 280px" />
                </div>
              </el-col>
            </el-row>
            <div class="mt3">
              <el-row class="mb10">
                <el-col :span="12">
                  <div class="flex-row">
                    年统计
                    <div class="label">时间：</div>
                    <el-date-picker
                      v-model="yearQuery.yearMonth"
                      type="year"
                      placeholder="请选择"
                      format="YYYY年"
                      value-format="YYYY"
                      @change="initYearStat"
                    />
                  </div>
                </el-col>
              </el-row>
              <el-row :gutter="50">
                <el-col :span="12">
                  <div
                    class="el-table el-table--enable-row-hover el-table--medium"
                  >
                    <div ref="consulttotalyear" style="height: 280px" />
                  </div>
                </el-col>
                <el-col :span="12">
                  <div
                    class="el-table el-table--enable-row-hover el-table--medium"
                    style="position: relative"
                  >
                    <div class="flex-row community-query">
                      <div>社区：</div>
                      <el-select
                        v-model="yearQuery.communityId"
                        :empty-values="[null]"
                        :value-on-clear="null"
                        placeholder="请选择社区"
                        size="large"
                        style="width: 160px"
                        clearable
                        @change="changeCommunity"
                      >
                        <el-option
                          v-for="dict in community_options"
                          :key="dict.id"
                          :label="dict.name"
                          :value="dict.id"
                        />
                      </el-select>
                    </div>
                    <div ref="consultstat" style="height: 280px" />
                  </div>
                </el-col>
              </el-row>
            </div>
          </template>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup name="ConsultationStatistics">
import {
  getConsultationStat,
  getUserConsultationStat,
  getUserConsultationStatSort,
} from "@/api/crowdInfo/consultation";
import { getCommunity } from "@/api/community/community";
import { listPoliceBySearch } from "@/api/community/police";
import {
  initConsulttotalmonthChart,
  initConsulttotalyearChart,
  initConsultstatChart,
  initUserEvaYearChart,
  initUserEvaNumSortChart,
} from "./chart";
import * as echarts from "echarts";
import dayjs from "dayjs";

const { proxy } = getCurrentInstance();
const current = ref(0);
const consulttotalmonth = ref(null);
const consulttotalyear = ref(null);
const consultstat = ref(null);
const community_options = ref([]);
const evayear = ref(null);
const evanum = ref(null);
const policeUserId = ref(undefined);
const polices = ref([]);
const data = reactive({
  monthQuery: {
    type: 0,
    yearMonth: dayjs(new Date()).format("YYYY-MM"),
  },
  yearQuery: {
    type: 1,
    yearMonth: String(new Date().getFullYear()),
    communityId: "",
  },
  userYears: dayjs(new Date()).format("YYYY"),
});
const { monthQuery, yearQuery, userYears } = toRefs(data);

function getList() {
  proxy.$modal.loading("正在加载咨询统计数据，请稍候！");
  initMonthStat();
  initYearStat();
  proxy.$modal.closeLoading();
}

// 社区选择改变
function changeCommunity() {
  getConsultationStat(yearQuery.value).then((response) => {
    const { data } = response;
    data.cstCmyMonthChartVos = data.cstCmyMonthChartVos ?? [];
    let xdata1 = [];
    let ydata1 = [];
    if (data.cstCmyMonthChartVos.length) {
      data.cstCmyMonthChartVos.forEach((item) => {
        xdata1.push(item.month);
        ydata1.push(+item.monthCount);
      });
    }
    // 咨询统计图
    const consultstatInstance = echarts.init(consultstat.value, "macarons");
    consultstatInstance.setOption(initConsultstatChart(xdata1, ydata1));

    window.addEventListener("resize", () => {
      consultstatInstance.resize();
    });
  });
}

/** 查询社区下拉列表数据 */
function getCommunityList() {
  getCommunity({}).then((response) => {
    const { data } = response;
    community_options.value = data;
    community_options.value.unshift({
      id: "",
      name: "全部",
    });
  });
}

// 咨询总数-月
function initMonthStat() {
  getConsultationStat(monthQuery.value).then((response) => {
    const { data } = response;
    const consulttotalmonthInstance = echarts.init(
      consulttotalmonth.value,
      "macarons"
    );
    data.cstCmyChartVos = data.cstCmyChartVos ?? [];
    let xdata = [];
    let ydata = [];
    let total = 0;
    if (data.cstCmyChartVos.length) {
      data.cstCmyChartVos.forEach((item) => {
        xdata.push(item.communityName);
        ydata.push(+item.communityCount);
        total += +item.communityCount;
      });
    }
    consulttotalmonthInstance.setOption(
      initConsulttotalmonthChart(xdata, ydata, total)
    );
    window.addEventListener("resize", () => {
      consulttotalmonthInstance.resize();
    });
  });
}

// 咨询总数-年
function initYearStat() {
  yearQuery.value.communityId = "";
  getConsultationStat(yearQuery.value).then((response) => {
    const { data } = response;
    // 咨询总数-年
    const consulttotalyearInstance = echarts.init(
      consulttotalyear.value,
      "macarons"
    );
    data.cstCmyChartVos = data.cstCmyChartVos ?? [];
    let xdata = [];
    let ydata = [];
    let total = 0;
    if (data.cstCmyChartVos.length) {
      data.cstCmyChartVos.forEach((item) => {
        xdata.push(item.communityName);
        ydata.push(+item.communityCount);
        total += +item.communityCount;
      });
    }
    consulttotalyearInstance.setOption(
      initConsulttotalyearChart(xdata, ydata, total)
    );

    data.cstCmyMonthChartVos = data.cstCmyMonthChartVos ?? [];
    let xdata1 = [];
    let ydata1 = [];
    if (data.cstCmyMonthChartVos.length) {
      data.cstCmyMonthChartVos.forEach((item) => {
        xdata1.push(item.month);
        ydata1.push(+item.monthCount);
      });
    }
    // 咨询统计图
    const consultstatInstance = echarts.init(consultstat.value, "macarons");
    consultstatInstance.setOption(initConsultstatChart(xdata1, ydata1));

    window.addEventListener("resize", () => {
      consulttotalyearInstance.resize();
      consultstatInstance.resize();
    });
  });
}

// 民警列表
function listPolice() {
  listPoliceBySearch({ key: "" })
    .then((response) => {
      const { data } = response;
      polices.value = data;
    })
    .catch((err) => {});
}

function initUserConStat() {
  proxy.$modal.loading("正在加载咨询统计数据，请稍候！");
  getUserConsultationStat({
    ...{ policeUserId: policeUserId.value },
    ...{ years: userYears.value },
  })
    .then((response) => {
      proxy.$modal.closeLoading();
      const { data } = response;
      nextTick(() => {
        // 评价总数
        const evayearInstance = echarts.init(evayear.value, "macarons");
        let xdata = [];
        let ydata = [];
        let chartData = data.yearVos ?? [];
        if (chartData.length) {
          chartData.forEach((item) => {
            xdata.push(item.month + "月");
            ydata.push(item.monthCount);
          });
        }
        evayearInstance.setOption(
          initUserEvaYearChart(
            xdata,
            ydata,
            `${data.userName ?? ""}-${data.badgeNumber ?? ""}`,
            data.sum ?? 0
          )
        );
        window.addEventListener("resize", () => {
          evayearInstance.resize();
        });
      });
    })
    .catch((err) => {
      proxy.$modal.closeLoading();
    });
}

// 纵向柱状图
function initUserConStatSort() {
  getUserConsultationStatSort({
    ...{ years: userYears.value },
  })
    .then((response) => {
      const { data } = response;
      let list = data ?? [];
      let xdata = [];
      let ydata = [];
      let comArr = [];
      if (list.length) {
        list.forEach((item) => {
          xdata.push(item.userName);
          ydata.push(item.communityCount);
          comArr.push(item.communityName);
        });
      }
      const evanumInstance = echarts.init(evanum.value, "macarons");
      evanumInstance.setOption(initUserEvaNumSortChart(xdata, ydata, comArr));

      window.addEventListener("resize", () => {
        evanumInstance.resize();
      });
    })
    .catch((err) => {
      proxy.$modal.closeLoading();
    });
}

function resetQuery() {
  policeUserId.value = undefined;
  userYears.value = dayjs(new Date()).format("YYYY");
  const evayearInstance = echarts.init(evayear.value, "macarons");
  evayearInstance.setOption(initUserEvaYearChart());
  window.addEventListener("resize", () => {
    evayearInstance.resize();
  });
  initUserConStatSort();
}

function getComData() {
  getList();
  getCommunityList();
}

function getUserList() {
  initUserConStat();
  initUserConStatSort();
}

onMounted(() => {
  listPolice();
  if (policeUserId.value) {
    getUserList();
  } else {
    const evayearInstance = echarts.init(evayear.value, "macarons");
    evayearInstance.setOption(initUserEvaYearChart());
    window.addEventListener("resize", () => {
      evayearInstance.resize();
    });
    initUserConStatSort();
  }
});
</script>

<style lang="scss" scoped>
.head {
  font-weight: bold;
  font-size: 1.5em;
  color: #000;
}
.flex-row {
  display: flex;
  flex-direction: row;
  align-items: center;
  font-size: 1rem;
  color: #000;
  .label {
    margin-left: 20px;
  }
}
.community-query {
  position: absolute;
  top: 0;
  left: 0;
  z-index: 10;
  :deep(.el-select__wrapper) {
    min-height: 32px;
  }
}
</style>
